package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author Maltyts
 * @url <a href="https://leetcode.cn/problems/find-bottom-left-tree-value/">...</a>
 */
public class BottomLeftTreeValue {
    private int maxDepth = Integer.MIN_VALUE;
    private int leftValue = 0;

    public int findBottomLeftValue(TreeNode root) {
        recursiveSolution(root, 1);
        return leftValue;
    }

    private void recursiveSolution(TreeNode root, int depth) {
        if (root.left == null && root.right == null) {
            leftValue = depth > maxDepth ? root.val : leftValue;
            maxDepth = depth > maxDepth ? depth : maxDepth;
        }
        if (root.left != null) {
            recursiveSolution(root.left, depth + 1);
        }
        if (root.right != null) {
            recursiveSolution(root.right, depth + 1);
        }
    }

    private int iterativeSolution(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int bottomLeftValue = 0;
        Queue<TreeNode> visited = new LinkedList<>();
        visited.add(root);
        while (!visited.isEmpty()) {
            int size = visited.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = visited.poll();
                if (i == 0) {
                    bottomLeftValue = node.val;
                }
                if (node.left != null) {
                    visited.offer(node.left);
                }
                if (node.right != null) {
                    visited.offer(node.right);
                }
            }
        }
        return bottomLeftValue;
    }


    public static void main(String[] args) {
        BottomLeftTreeValue bottomLeftTreeValue = new BottomLeftTreeValue();
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(1);
        root.right = new TreeNode(3);
//        root.left.left = new TreeNode(4);
//        root.right.left = new TreeNode(5);

        int bottomLeftValue = bottomLeftTreeValue.findBottomLeftValue(root);
        System.out.println(bottomLeftValue);
    }
}
